<template>
  <div class="account-page">
    <div class="alert alert-danger" v-if="error">{{ error }}</div>
    <div class="alert alert-success" v-if="successMessage">{{ successMessage }}</div>
    
    <div class="account-info card">
      <h3>账户信息</h3>
      <div class="info-item">
        <label>用户名</label>
        <div>{{ user.username }}</div>
      </div>
      <div class="info-item">
        <label>邮箱</label>
        <div>{{ user.email }}</div>
      </div>
      <div class="info-item">
        <label>角色</label>
        <div>{{ user.role === 'admin' ? '管理员' : '用户' }}</div>
      </div>
    </div>
    
    <div class="password-change card">
      <h3>修改密码</h3>
      <form @submit.prevent="changePassword">
        <div class="form-group">
          <label for="currentPassword">当前密码</label>
          <input 
            type="password" 
            id="currentPassword" 
            v-model="passwordForm.currentPassword" 
            required
            placeholder="输入当前密码"
          />
        </div>
        
        <div class="form-group">
          <label for="newPassword">新密码</label>
          <input 
            type="password" 
            id="newPassword" 
            v-model="passwordForm.newPassword" 
            required
            placeholder="输入新密码"
          />
          <div class="password-requirements">
            密码长度至少为6个字符
          </div>
        </div>
        
        <div class="form-group">
          <label for="confirmPassword">确认新密码</label>
          <input 
            type="password" 
            id="confirmPassword" 
            v-model="passwordForm.confirmPassword" 
            required
            placeholder="再次输入新密码"
          />
        </div>
        
        <div class="form-error" v-if="passwordError">
          {{ passwordError }}
        </div>
        
        <div class="form-actions">
          <button type="submit" class="save-btn" :disabled="isSubmitting">
            {{ isSubmitting ? '保存中...' : '保存新密码' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { authService } from '../../services';

export default {
  setup() {
    const router = useRouter();
    const user = ref({
      username: '',
      email: '',
      role: ''
    });
    
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    
    const error = ref('');
    const successMessage = ref('');
    const passwordError = ref('');
    const isSubmitting = ref(false);
    
    // 加载用户信息
    const loadUserInfo = async () => {
      try {
        const currentUser = authService.getCurrentUser();
        
        if (currentUser) {
          user.value = currentUser;
        } else {
          // 如果本地没有用户信息，尝试从API获取
          const response = await authService.getProfile();
          if (response && response.user) {
            user.value = response.user;
          }
        }
      } catch (err) {
        console.error('获取用户信息失败:', err);
        error.value = '获取用户信息失败';
        
        // 如果获取失败，可能是未登录或令牌过期，重定向到登录页
        setTimeout(() => {
          authService.logout();
          router.push({ name: 'admin-login' });
        }, 2000);
      }
    };
    
    // 修改密码
    const changePassword = async () => {
      // 清除之前的错误和成功消息
      passwordError.value = '';
      error.value = '';
      successMessage.value = '';
      
      // 验证新密码
      if (passwordForm.newPassword.length < 6) {
        passwordError.value = '新密码长度必须至少为6个字符';
        return;
      }
      
      // 验证两次输入的密码是否一致
      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        passwordError.value = '两次输入的密码不一致';
        return;
      }
      
      try {
        isSubmitting.value = true;
        
        // 调用API修改密码
        await authService.changePassword(
          passwordForm.currentPassword,
          passwordForm.newPassword
        );
        
        // 密码修改成功
        successMessage.value = '密码修改成功';
        
        // 清空表单
        passwordForm.currentPassword = '';
        passwordForm.newPassword = '';
        passwordForm.confirmPassword = '';
        
        // 3秒后清除成功消息
        setTimeout(() => {
          successMessage.value = '';
        }, 3000);
      } catch (err) {
        if (err.response && err.response.status === 401) {
          passwordError.value = '当前密码错误';
        } else {
          error.value = err.response?.data?.message || '修改密码失败，请稍后再试';
        }
        console.error('修改密码失败:', err);
      } finally {
        isSubmitting.value = false;
      }
    };
    
    // 初始化
    onMounted(() => {
      loadUserInfo();
    });
    
    return {
      user,
      passwordForm,
      error,
      successMessage,
      passwordError,
      isSubmitting,
      changePassword
    };
  }
}
</script>

<style scoped>
.account-page {
  max-width: 800px;
  margin: 0 auto;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 30px;
}

.card h3 {
  margin-top: 0;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
  color: #343a40;
}

.account-info {
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
}

.info-item label {
  width: 100px;
  font-weight: 500;
  color: #6c757d;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 16px;
}

.form-group input:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.password-requirements {
  margin-top: 5px;
  font-size: 0.85rem;
  color: #6c757d;
}

.form-error {
  padding: 10px;
  margin-bottom: 20px;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  color: #721c24;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
}

.save-btn {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #218838;
}

.save-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.alert {
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.alert-danger {
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  color: #721c24;
}

.alert-success {
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  color: #155724;
}
</style> 